package cn.edu.mju.controller;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CaptcheController extends ActionSupport implements ServletResponseAware{
	private HttpServletResponse response;
	
	public String captche()
	{
		int width=80;
		int height = 20;
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = img.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		g.setColor(Color.RED);
		String code = rndCode(4);
		g.drawString(code, 5, 10);
		g.dispose();
		 try {
			ServletOutputStream sos = response.getOutputStream();
			ImageIO.write(img, "JPEG", sos);
			sos.flush();
			sos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}

	private String rndCode(int count)
	{
		String txt="3456789abcdefghijkmnpqrstuvwxy";
		StringBuffer sb = new StringBuffer();
		Random rnd = new Random();
		for(int i=0;i<count;i++)
		{
			int index = rnd.nextInt(txt.length());
			sb.append(txt.charAt(index));
		}
		String code = sb.toString();
		ActionContext.getContext().getSession().put("code", code);
		return code;
	}
}
